﻿@model RH.Web.ViewModels.ProductViewModel
@using RH.Web.Utility;
@using RH.Common.Extensions;

@{
    String pageTitle = "Edit Property & Manage Property Images";
    if (Model != null && Model.ID == 0)
    {
        pageTitle = "Add New Property";
    }
    ViewBag.Title = Html.GetPageTitle(pageTitle);
    String categoryButtonText = Model.CategoryID > 0 ? "Change Category" : "Select Category";
    //String _SaveButtonCaption = Model.ID == 0 ? "Save" : "Save";
    List<RH.Web.ViewModels.CategoryViewModel> _Categories = ApplicationCache.Categories;
    bool _IsSaved = TempData[AppConstants.ViewDataKeys.SAVED] == null ? false : TempData[AppConstants.ViewDataKeys.SAVED].ToString().ToBoolean();
    bool _IsAdded = TempData[AppConstants.ViewDataKeys.ADDED] == null ? false : TempData[AppConstants.ViewDataKeys.ADDED].ToString().ToBoolean();
    bool _HasValidationError = ViewData[AppConstants.ViewDataKeys.HAS_VALIDATION_ERROR] != null ? true : false;
    if (Model.Address == null) {
        Model.Address = new RH.Web.ViewModels.AddressViewModel();        
    }
    Model.Address.IsMinimalView = true;
    
    ViewData[AppConstants.ViewDataKeys.SELECTED_MENU] = CompanyMenu.Projects;
}

<div class="rh-page-heading">
    <h1>@pageTitle</h1>
    <div>
        Enter necessary information and then Upload Images (If Any) for this property.
    </div>
</div>
<div class="rh-page-content">
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(false)
        Html.EnableClientValidation(true);
        if (Model == null)
        {
            @: @Html.ErrorMessageBox("Sorry! Requested Property was not found for edit.")
        }
        else
        {
            if (_IsAdded)
            {
                @: @Html.SuccessMessageBox("Property added successfully. Now add few images and address for this property to increase visibility and accessibility to your customers. Just click the Add button next to the Image and Address section.", "Congrats!")
            }
            else if (_IsSaved)
            {
                @: @Html.SuccessMessageBox("Property Saved Successfully.")
        }
        @Html.HiddenFor(model => model.ID)

        <div class="col-md-6 rh-gridfix">
            <div class="rh-group-title">Basic Property Information</div>
            <div class="col-md-8 rh-gridfix">
                <div class="editor-label">
                    @Html.LabelFor(model => model.CategoryID)
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(model => model.CategoryID, BindSelectList.Categories())
                    @Html.ValidationMessageFor(model => model.CategoryID)
                </div>
            </div>
            <div class="col-lg-4 rh-gridfix">
                <div class="editor-label">&nbsp;</div>
                <div class="">
                    <label>@Html.CheckBoxFor(model => model.IsForRent) Is For Rent?</label>
                </div>
            </div>
            <div class="clearfix"></div>
            
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
                <div class="rh-label-hint">Enter a brief, informative and easily understandable title. So that users can pick your advertisement very quickly just reading the title.</div>
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.Name, new { @class = "rh-long-text" })
                @Html.ValidationMessageFor(model => model.Name)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Price)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Description)
            </div>
            <div class="editor-field">
                @Html.TextAreaFor(model => model.Description, new { @class = "rh-long-text" })
                @*@Html.EditorFor(model => model.Description)*@
                @Html.ValidationMessageFor(model => model.Description)
            </div>

            @if (_HasValidationError)
            {
                @Html.Hidden("hdnSelectedValues", Model.ZGLPayloadXml.UrlEncode(), new { id = "hdnSelectedValues"})
            }            
        </div>
        @*Right Column Starts here*@
        <div class="col-md-6 rh-gridfix">            
            @if (Model.ID > 0)
            {
                <div class="rh-group-title">Manage Property Images</div>
                <div id="divImageGallery">
                    @{String buttonCaption = "<i class=\"glyphicon glyphicon-edit\"></i> Edit ";}
                    @if (Model.ProductImages == null || Model.ProductImages.Count <= 0) {
                        buttonCaption = "<i class=\"glyphicon glyphicon-plus\"></i> Add ";
                        <img id="imgNoImage" src="@ImageManager.GetProductImageUrl(String.Empty, 0)" />
                    }
                    @foreach (var image in Model.ProductImages) {
                        <a href="@ImageManager.GetProductImageUrl(image.Picture, image.ProductID)" title="@image.Picture" data-gallery="">
                            <img src="@ImageManager.GetProductImageUrl(image.Thumbnail, image.ProductID)">
                        </a>
                    }
                </div>
                <div class="rh-top-5px">
                    <button id="btnImageDialog" type="button" class="btn btn-default btn-sm">@MvcHtmlString.Create(buttonCaption) </button>
                </div>
            
                <div class="rh-group-title">Property Address</div>
                <span id="spnAddress">@Html.BuildAddressHtml(Model.Address)</span>
                
                String buttonId = "btnAddressEdit";
                <div>
                    @if (Model.Address.ID == 0)
                    {
                        //Model.Address = new RH.Web.ViewModels.AddressViewModel(); ///To prevent failure in AddressViewModelTemplate
                        //Model.Address.IsMinimalView = true;
                        <button id="@buttonId" type="button" class="btn btn-default btn-sm"><i class="glyphicon glyphicon-plus"></i> Add </button>
                    }
                    else
                    {
                        <button id="@buttonId" type="button" class="btn btn-default btn-sm"><i class="glyphicon glyphicon-edit"></i> Edit </button>
                    }
                </div>
            }
        </div>
        <div class="clearfix"></div>
        @*Right Column Ends Here*@
        <div class="row">
            <div class="col-md-4"><div id="divZGL_form_col_1"></div></div>
            <div class="col-md-4"><div id="divZGL_form_col_2"></div></div>
            <div class="col-md-4"><div id="divZGL_form_col_3"></div></div>
            <div class="clearfix"></div>
        </div>
        <div class="rh-button-container">
            <button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
            <a href="@Url.PrivateUrl("List", "Product")" class="btn btn-default"><i class="glyphicon glyphicon-arrow-left"></i> Back to List</a>
        </div>
        }
    }
</div>

@*Manage Image Dialog*@
<div class="modal fade" id="divImageDialog2" tabindex="-1" role="dialog" aria-labelledby="modalPropertyImages" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Manage Property Images</h4>
            </div>
            <div class="modal-body">
                <iframe id="iframeImageList" scrolling="no" frameborder="0" src="" style="width:100%;"></iframe>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> Close</button>
                @*<button type="button" class="btn btn-primary"><i class="glyphicon glyphicon-ok"></i> Save</button>*@
            </div>
        </div>
    </div>
</div>
@*Manage Image Dialog End*@
@*Address Modal Start *@
<div class="modal fade" id="divAddressDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Manage Property Address</h4>
            </div>
            <div class="modal-body">
                @Html.EditorFor(model => model.Address)
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> Close</button>
                <button type="button" class="btn btn-primary" onclick="SaveAddress();"><i class="glyphicon glyphicon-ok"></i> Save</button>
            </div>
        </div>
    </div>
</div>
@*Address Modal End *@

@*The modal dialog, which will be used to wrap the lightbox content*@
<div id="blueimp-gallery" class="blueimp-gallery">
    <!-- The container for the modal slides -->
    <div class="slides"></div>
    <!-- Controls for the borderless lightbox -->
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
    <!-- The modal dialog, which will be used to wrap the lightbox content -->
    <div class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" aria-hidden="true">&times;</button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body next"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default pull-left prev">
                        <i class="glyphicon glyphicon-chevron-left"></i>
                        Previous
                    </button>
                    <button type="button" class="btn btn-primary next">
                        Next
                        <i class="glyphicon glyphicon-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
@*End of Modal Dialog*@

@section PageHeadSection
{
    @Styles.Render("~/Content/imagegallerycss")
    <style type="text/css">
        #divImageDialog2 .modal-body{padding:0px; min-height:300px;}
        #divImageGallery img{margin-bottom:3px;}
    </style>
    @*<link rel="stylesheet" href="@Url.Content("~/Content/lightbox.css")" type="text/css" />
    @Html.JavaScript("lightbox.js", Url)
     Removed for testing but it turned out that without these lightbox is working.
        @Html.JavaScript("jquery-ui-1.8.18.custom.min.js", Url)
        @Html.JavaScript("jquery.smooth-scroll.min.js", Url)*@
}

@section JavaScriptPlaceholder
{
    @Scripts.Render("~/bundles/jqueryval", "~/bundles/imagegalleryjs")
    @Html.Partial("_DatePicker", String.Empty)
    @if (Model != null)
    {
        <script language="javascript" type="text/javascript">

            //var _CategoryDialog = null;
            var _PictureDialog = null;
            //var _ImageDialog = null;
            $(document).ready(function () {
                $('#btnAddressEdit').click(function () {
                    $('#divAddressDialog').modal({ show: true });
                });
                $('#btnImageDialog').click(function () {                    
                    $('#divImageDialog2').modal({ show: true });
                    var iFrame = $('#divImageDialog2').find('iframe');
                    if ($(iFrame).attr('src').length == 0) {
                        ShowLoadingAnimation(false);
                        $(iFrame).attr('src', '@Url.Action("List", "ProductImage", new { ID = Model.ID })');
                    }
                });
                $('#CategoryID').change(function () {
                    GetDynamicProperties(@Model.ID, $(this).val());
                });
                if($('#CategoryID').val() > 0)
                    GetDynamicProperties(@Model.ID, $('#CategoryID').val());
            });
            function GetDynamicProperties(productID, categoryID) {
                ShowLoadingAnimation(false);
                var url = '@Url.Action("GetDynamicUI", "Product", new { area = AppConstants.Area.PRIVATE })';
                //alert('The Url Is: ' + url);
                var data = 'productID=' + productID + '&categoryID=' + categoryID;
                //var data = {};
                var lglValues = $('#hdnSelectedValues').val();
                if (lglValues != undefined && lglValues != null && lglValues.length > 0)
                    data += '&lglValues=' + lglValues;
                    //data = {lglValues: lglValues}; 
                Ajax(url, data, function (result) {
                    var dom = $('<div>').append(result);
                    var groups = $(dom).find('.rh-dp-group');                    
                    for(var i = 0; i < groups.length; i++){
                        if((i % 3) == 0 )
                            $('#divZGL_form_col_1').append(groups[i]);
                        else if((i % 3) == 1)
                            $('#divZGL_form_col_2').append(groups[i]);
                        else
                            $('#divZGL_form_col_3').append(groups[i]);
                    }
                    //$('#divDynamicProperty').html(result);
                    var form = $('form');
                    $(form).removeData('validator');
                    $.validator.unobtrusive.parse(form);
                    HideLoadingAnimation();
                });
            }            
            function UpdateImageList(thumbnail, largePicture) {
                $('#divImageGallery').show();
                var html = '';
                //var imgElements = $('#divImageGallery img');
                html += BuildLightboxImageElement(thumbnail, largePicture);
                $('#divImageGallery').append(html);
                var noImage = $('#imgNoImage');
                if( noImage != null)
                    $(noImage).remove();
                
                $('#btnImageDialog').html('<i class="glyphicon glyphicon-edit"></i> Edit');
            }
            function DeleteFromImageList(thumbnail) {
                var elementToRemove = null;
                $('#divImageGallery').find('img').each(function () {
                    if ($(this).attr('src') == thumbnail) {
                        elementToRemove = $(this).closest('a');
                    }
                });
                if (elementToRemove != null)
                    $(elementToRemove).remove();

                var imgElements = $('#divImageGallery img');
                if (imgElements.length == 0) {
                    $('#divImageGallery').html('<img id="imgNoImage" src="@ImageManager.GetProductImageUrl(String.Empty, 0)"/>');
                    $('#btnImageDialog').html('<i class="glyphicon glyphicon-plus"></i> Add');                    
                }
            }
            function BuildLightboxImageElement(thumbnail, largePicture) {
                //return '<div class="single"><a href="' + largePicture + '" rel="lightbox[ProductAlbum]" title="Click on the Right/Left side of the image to move Forward/Reverse."><img src="' + thumbnail + '" alt="Image 3 0f 3 thumb" /></a></div>';
                return '<a href="'+ largePicture + '" title="Let\'s call it a day" data-gallery="">' +
                            '<img src="' + thumbnail + '"/>' +
			            '</a>';
            }
            function AdjustiFrameHeight(height) {
                $('#iframeImageList').height(height);
            }
            function ChildHideLoading() {
                HideLoadingAnimation();
            }

            var _pfx = $('#@AppConstants.UI.DIV_ADDRESS_FIELD_PREFIX').html();
            function SaveAddress() {
                var data = { ID: AddressValue('ID'), StreetAddress: encodeURIComponent(AddressValue('StreetAddress')), CountryID: AddressValue('CountryID'), DistrictID: AddressValue('DistrictID'), LocationID: AddressValue('LocationID') };
                ShowLoadingAnimation(false);
                Ajax('@Url.PrivateUrl("SaveAddress", "Product")?productId=' + $('#ID').val(), data, function (result) {
                    if (result.length > 0) {
                        var parts = result.split('[*ADDRESS_ID*]');
                        $('#' + _pfx + '_ID').val(parts[0]);
                        $('#spnAddress').html(parts[1]);
                        $('#btnAddressEdit').html('<i class="glyphicon glyphicon-edit"></i> Edit');
                        HideLoadingAnimation();
                        $('#divAddressDialog').modal('hide');
                    }
                });
            }
            function AddressValue(id) {
                return $('#' + _pfx + '_' + id).val();
            }
        </script>
    }
}


